package com.yanx.system.base.domain.manager;

import com.yanx.common.core.domain.manager.BaseManager;
import com.yanx.system.base.domain.entity.SysUser;
import com.yanx.system.base.domain.repository.SysUserRepository;
import org.springframework.stereotype.Service;

/**
 * 用户领域服务
 *
 * @author: gotanks
 * @create: 2023-2-6
 */
@Service
public class SysUserManager extends BaseManager<SysUser, SysUserRepository> {

    public SysUser getByUserName(String username) {
        return repository.findByUserName(username);
    }

    public boolean checkUserNameUnique(String userName, Long id) {
        int num = repository.countByUserNameAndIdNot(userName, id);
        return num > 0;
    }

    public boolean checkPhoneUnique(String phonenumber, Long id) {
        int num = repository.countByPhonenumberAndIdNot(phonenumber, id);
        return num > 0;
    }

    public boolean checkEmailUnique(String email, Long id) {
        int num = repository.countByEmailAndIdNot(email, id);
        return num > 0;
    }

    public void addUserRoles(Long userId, Long[] roleIds) {
        repository.findById(userId).ifPresent(user -> {
            for (Long roleId : roleIds) {
                user.addUserRole(userId, roleId);
            }
            repository.save(user);
        });
    }
}
